// pages/category/index.ts
import {
  request
} from '../../request/index'
Page({
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    var cates = wx.getStorageSync('cates')
    if (!cates) {
      this.getcategories()
    } else {
      // 当时间超过10s 重新发送请求
      if (Date.now() - cates.time > 10000) {
        this.getcategories()
      } else {
        // 没超过10s就可以 用 旧数据
        this.cates = cates.data
        let leftMenuList = this.cates.map(s => s.cat_name)
        let categorieLists = this.cates[0].children
        this.setData({
          leftMenuList: leftMenuList,
          categorieLists: categorieLists
        })
      }
    }
  },
  /**
   * 页面的初始数据
   */
  data: {
    leftMenuList: [],
    categorieLists: [],
    // 被点击的左侧菜单
    mainActiveIndex: 0,
    rightContent: 0,
    rightLocation: 0
  },
  cates: [],
  getcategories() {
    request({
      url: `categories`
    }).then(res => {
      this.cates = res
      let leftMenuList = this.cates.map(s => s.cat_name)
      let categorieLists = this.cates[0].children
      this.setData({
        leftMenuList: leftMenuList,
        categorieLists: categorieLists
      })
      wx.setStorageSync('cates', {
        data: res,
        time: Date.now()
      })
      console.log(categorieLists)
    })
  },
  chooseMenu(index) {
    let indexitem = index.currentTarget.dataset.index
    this.setData({
      mainActiveIndex: indexitem,
      categorieLists: this.cates[indexitem].children,
      // 离顶部的距离
      rightLocation: 0
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})